import { defineEventHandler, readBody, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const { parentId, name, content } = await readBody(event);

    const db = await getDbConnection();
    const result = await db.run(
      `INSERT INTO notes (name, content, user_id, parent_id) 
       VALUES (?, ?, ?, ?)`,
      [name || '新建笔记', content || '# 新建笔记', userId, parentId ?? null]
    );

    const newNoteId = result.lastID;
    const newNote = await db.get(
      `SELECT id, name, content, created_at, updated_at 
       FROM notes 
       WHERE id = ?`,
      [newNoteId]
    );

    return newNote;
  } catch (error) {
    console.error('Error creating new note:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to create note' });
  }
});
